package com.song.EMS.wx.controller;

import com.song.EMS.bean.Courier;
import com.song.EMS.bean.User;
import com.song.EMS.service.impl.CourierServiceImpl;
import com.song.EMS.service.impl.UserServiceImpl;
import com.song.EMS.wx.controller.bean.Role;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class UserUtils {
    /**
     * 存储用户登录时验证码
     * @param request 请求
     * @param loginCode 验证码
     */
     public static void setUserCode(HttpServletRequest request, String loginCode){
         request.getSession().setAttribute("loginCode",loginCode);
     }

    /**
     * 获取session中存储的验证码
     * @param request
     * @return
     */
     public static String getUserCode(HttpServletRequest request){
         return (String) request.getSession().getAttribute("loginCode");
     }

    /**
     * 再session中存储用户登录时的手机号码
     * @param request 登录时的请求
     * @param phone 用户手机号
     */
    public static void setUserPhone(HttpServletRequest request,String phone) {
        HttpSession session = request.getSession();
        session.setAttribute("userPhone",phone);
    }

    /**
     * 获取用户登录的手机号
     * @param request
     * @return 用户的手机号
     */
    public static String getUserPhone(HttpServletRequest request){
        return (String) request.getSession().getAttribute("userPhone");
    }

    /**
     * 通过用户登录的手机号判断该用户的身份
     * 1 快递员   2 普通用户  0新用户
     * @param request 请求
     * @param userPhone 登录人的手机号
     * @return 登录人的信息
     */
    public static void setRole(HttpServletRequest request,String userPhone){
        Role role = null;
        CourierServiceImpl courierService = new CourierServiceImpl();
        UserServiceImpl userService = new UserServiceImpl();

        Courier courier = courierService.selectByPhone(userPhone);
        User user = userService.selectByPhone(userPhone, null);
        if (courier != null){
            role = new Role(1,courier);
        }else if (user != null){
            role = new Role(2,user);
        }else{
            User user1 = new User();
            user1.setUserPhone(userPhone);
            role = new Role(0,user1);
        }
        request.getSession().setAttribute("role",role);
    }

    public static Role getRole(HttpServletRequest request){
        Object role = request.getSession().getAttribute("role");
        return (Role) role;
    }
}
